package com.example.sunmiv1.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sunmiv1.R;
import com.example.sunmiv1.adapter.AddDepositAdapter;
import com.example.sunmiv1.adapter.EditDepositAdapter;
import com.example.sunmiv1.base.BaseActivity;
import com.example.sunmiv1.entity.DepositGoodsEditInfo;
import com.example.sunmiv1.entity.DepositGoodsInfo;
import com.example.sunmiv1.entity.StoreWarehouseInfo;
import com.example.sunmiv1.utils.LogUtil;
import com.example.sunmiv1.utils.Tools;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.GsonUtils;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.LoadingDialog;
import com.example.sunmiv1.utils.net.TextCallBack;
import com.example.sunmiv1.utils.zxing.Constant;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

// 採購管理.採購單.新增採購單|| 編輯
public class PurchaseOrderAddActivity extends BaseActivity {


    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_title)
    TextView titleTitle;
    @BindView(R.id.btn_to_top)
    ImageView btnToTop;
    @BindView(R.id.addPurchase_chooseFood)
    LinearLayout addPurchaseChooseFood;
    @BindView(R.id.addPurchaseSearch_edit)
    EditText addPurchaseSearchEdit;
    @BindView(R.id.addPurchaseSearch_code)
    ImageView addPurchaseSearchCode;
    @BindView(R.id.addPurchaseSearch_search)
    ImageView addPurchaseSearchSearch;
    @BindView(R.id.purchaseOrder_type)
    Spinner purchaseOrderType;
    @BindView(R.id.purchaseOrder_warehouse)
    Spinner purchaseOrderWarehouse;
    @BindView(R.id.purchaseOrder_supplies)
    Spinner purchaseOrderSupplies;
    @BindView(R.id.addPurchase_screenLin)
    LinearLayout addPurchaseScreenLin;
    @BindView(R.id.addPurchase_remark)
    EditText addPurchaseRemark;
    @BindView(R.id.addPurchase_remarkLin)
    LinearLayout addPurchaseRemarkLin;
    @BindView(R.id.addPurchase_listView)
    ListView addPurchaseListView;
    @BindView(R.id.addPurchase_checkAll)
    TextView addPurchaseCheckAll;
    @BindView(R.id.addPurchase_submit)
    TextView addPurchaseSubmit;
    @BindView(R.id.addPurchase_complete)
    TextView addPurchaseComplete;
    @BindView(R.id.addPurchase_delete)
    TextView addPurchaseDelete;
    @BindView(R.id.addPurchase_operation)
    LinearLayout addPurchaseOperation;
    @BindView(R.id.addPurchaseSearch_searchLin)
    LinearLayout addPurchaseSearchSearchLin;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.purchaseOrder_parchase_time)
    LinearLayout purchaseOrderParchaseTime;
    @BindView(R.id.addPurchase_scanFood)
    LinearLayout addPurchaseScanFood;
    @BindView(R.id.addPurchase_chooseLin)
    LinearLayout addPurchaseChooseLin;

    private ACache aCache;
    private LoadingDialog loadingDialog;
    private List<DepositGoodsInfo.DataBean.ListBean> choiceList = new ArrayList<>();
    private List<DepositGoodsEditInfo.DataBean> editInfoList = new ArrayList<>();
    //
    private boolean opera = false;//是否操作
    private AddDepositAdapter addDepositAdapter;
    private EditDepositAdapter editDepositAdapter;
    private ArrayList<String> notInIdArr;// 已在此頁的貨物id  添加和選擇2個頁面都要維護這個列表


    private List<String> typeList = new ArrayList<>();//類型集合
    private int typeIndex = 0;//選擇的類型下標

    private StoreWarehouseInfo storeWarehouseInfo;
    private List<String> warehouseNameList = new ArrayList<>();//倉庫名稱集合
    private List<StoreWarehouseInfo.WarehouseListBean> warehouseList = new ArrayList<>();//倉庫集合
    private int warehouseIndex = 0;//選擇的倉庫下標

    private List<String> suppliesNameList = new ArrayList<>();//供應商名稱集合
    private List<StoreWarehouseInfo.SupplierListBean> suppliesList = new ArrayList<>();//供應商集合
    private int suppliesIndex = 0;//選擇的供應商下標

    private int type = 0;//0 門店新增採購單 ,1 門店編輯採購單,2 商戶新增採購單,3 商戶編輯採購單
    private boolean isedit = false;// true爲編輯頁
    private String time = "";

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    warehouseList.add(new StoreWarehouseInfo.WarehouseListBean("", "所有倉庫"));
                    warehouseNameList.add("所有倉庫");
                    for (StoreWarehouseInfo.WarehouseListBean warehouseListBean : storeWarehouseInfo.getWarehouseList()) {
                        warehouseList.add(warehouseListBean);
                        warehouseNameList.add(warehouseListBean.getName());
                    }
                    suppliesList.add(new StoreWarehouseInfo.SupplierListBean("", "所有供貨商"));
                    suppliesNameList.add("所有供貨商");
                    for (StoreWarehouseInfo.SupplierListBean supplierListBean : storeWarehouseInfo.getSupplierList()) {
                        suppliesList.add(supplierListBean);
                        suppliesNameList.add(supplierListBean.getSupplier_name());
                    }
                    setWarehouseAdapter();
                    setSuppliesAdapter();
                    break;
                case 2:
                    warehouseList.add(new StoreWarehouseInfo.WarehouseListBean("", "所有倉庫"));
                    warehouseNameList.add("所有倉庫");
                    setWarehouseAdapter();
                    suppliesList.add(new StoreWarehouseInfo.SupplierListBean("", "所有供貨商"));
                    suppliesNameList.add("所有供貨商");
                    setSuppliesAdapter();
                    break;
                case 3:
                    setEditDepositAdapter();
                    break;
                case 4:
                    break;
            }
        }
    };

    @Override
    protected void initView() {
        setContentView(R.layout.activity_purchase_order_add);
        ButterKnife.bind(this);
        aCache = ACache.get(this);
        loadingDialog = new LoadingDialog(this);
        type = getIntent().getIntExtra("type", 0);
        isedit = getIntent().getBooleanExtra("isedit", false);
        LogUtil.e("initView():" + type);
        if (type == 0 || type == 2) {//門店新增採購單||商戶新增採購單
            titleTitle.setText(R.string.purchaseOrderAdd1);
        } else if (type == 1 || type == 3) {
            titleTitle.setText(R.string.purchaseOrderAdd2);
            addPurchaseSubmit.setText(R.string.purchaseOrderAdd3);
            addPurchaseChooseLin.setVisibility(View.GONE);
            addPurchaseSearchSearchLin.setVisibility(View.GONE);
            addPurchaseScreenLin.setVisibility(View.VISIBLE);
            addPurchaseCheckAll.setVisibility(View.GONE);
            purchaseOrderType.setVisibility(View.GONE);
            addPurchaseRemarkLin.setVisibility(View.VISIBLE);
            getPurchaseOrderDetail();
        } else {//  其他
            titleTitle.setText(R.string.purchaseOrderAdd4);
        }
    }

    @Override
    protected void initData() {
        getStoreWarehouseInfo();
        typeList.add(getString(R.string.purchaseOrderAddList1));
        typeList.add(getString(R.string.purchaseOrderAddList2));
        typeList.add(getString(R.string.purchaseOrderAddList3));
        notInIdArr = new ArrayList<>();
        setAddDepositAdapter();
        setWarehouseAdapter();
        setTypeAdapter();
    }

    @Override
    protected void initListener() {
        purchaseOrderType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (type == 0 || type == 2) {
                    if (2 == position) {
                        purchaseOrderParchaseTime.setVisibility(View.VISIBLE);
                    } else {
                        purchaseOrderParchaseTime.setVisibility(View.GONE);
                    }
                }
                typeIndex = position;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        purchaseOrderWarehouse.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                warehouseIndex = position;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        purchaseOrderSupplies.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                suppliesIndex = position;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    /**
     * 類型適配器
     */
    private void setTypeAdapter() {
        ArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.item_drop, typeList);
        arrayAdapter.setDropDownViewResource(R.layout.item_drops);
        purchaseOrderType.setAdapter(arrayAdapter);
    }

    /**
     * 採購倉適配器
     */
    private void setWarehouseAdapter() {
        ArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.item_drop, warehouseNameList);
        arrayAdapter.setDropDownViewResource(R.layout.item_drops);
        purchaseOrderWarehouse.setAdapter(arrayAdapter);
    }

    /**
     * 供應倉適配器
     */
    private void setSuppliesAdapter() {
        ArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.item_drop, suppliesNameList);
        arrayAdapter.setDropDownViewResource(R.layout.item_drops);
        purchaseOrderSupplies.setAdapter(arrayAdapter);
    }


    /**
     * 選擇的商品的適配器
     */
    private Intent intent;

    private void setAddDepositAdapter() {
        if (addDepositAdapter == null) {
            addDepositAdapter = new AddDepositAdapter(this, choiceList, type);
            addPurchaseListView.setAdapter(addDepositAdapter);
        } else {
            addDepositAdapter.notifyDataSetChanged();
        }
        addDepositAdapter.setChoose(index -> {
            intent = new Intent(context, StringCodeOperationActivity.class);
            intent.putExtra("operation", 7);
            intent.putExtra("good", choiceList.get(index));
            ArrayList<String> serialList = new ArrayList<>();
            for (DepositGoodsInfo.DataBean.ListBean bean : choiceList) {
                if ("1".equals(bean.getSerial_number_state())) {
                    for (DepositGoodsInfo.DataBean.ListBean.SerialBean b : bean.getSerialList()) {
                        serialList.add(b.getMain_serial_number());
                        if (!TextUtils.isEmpty(b.getAuxiliary_serial_number_one())) {
                            serialList.add(b.getAuxiliary_serial_number_one());
                        }
                        if (!TextUtils.isEmpty(b.getAuxiliary_serial_number_two())) {
                            serialList.add(b.getAuxiliary_serial_number_two());
                        }
                    }
                }
            }
            intent.putStringArrayListExtra("list", serialList);
            startActivityForResult(intent, 200);
        });
    }

    /**
     * 編輯的商品的適配器
     */
    private void setEditDepositAdapter() {
        if (editDepositAdapter == null) {
            editDepositAdapter = new EditDepositAdapter(this, editInfoList);
            addPurchaseListView.setAdapter(editDepositAdapter);
        } else {
            editDepositAdapter.notifyDataSetChanged();
        }
        editDepositAdapter.setChoose(index -> {
            intent = new Intent(context, StringCodeOperationActivity.class);
            intent.putExtra("operation", 11);
            intent.putExtra("good", editInfoList.get(index));
            startActivityForResult(intent, 300);
        });
    }

    /**
     * 獲取採購倉與供貨商信息
     */
    private void getStoreWarehouseInfo() {
        JSONObject jsonObject = new JSONObject();
        try {
            String url = "";
            if (type == 3 || type == 2) {
//                if(isedit){
//                    url=
//                }else
                url = Common.MER_WAREHOUSE_INFO;
            } else {
                url = Common.STORE_WAREHOUSE_INFO;
            }
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            HttpUtils.post(this, url, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    storeWarehouseInfo = GsonUtils.JsonToBean(text, StoreWarehouseInfo.class);
                    Message msg = new Message();
                    if (storeWarehouseInfo.getStatus() == 1) {
                        msg.what = 1;
                    } else {
                        msg.what = 2;
                    }
                    handler.sendMessage(msg);
                }

                @Override
                protected void onFailure(ResponseException e) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    @OnClick({R.id.title_back, R.id.btn_to_top, R.id.purchaseOrder_parchase_time, R.id.addPurchase_chooseFood, R.id.addPurchase_scanFood,
            R.id.addPurchaseSearch_code, R.id.addPurchaseSearch_search, R.id.addPurchase_checkAll, R.id.addPurchase_submit,
            R.id.addPurchase_complete, R.id.addPurchase_delete, R.id.addPurchase_operation})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.btn_to_top:
                addPurchaseListView.setSelection(0);
                break;
            case R.id.addPurchase_chooseFood:
                Intent intent = new Intent(this, DepositGoodsActivity.class);
                intent.putStringArrayListExtra("not_in_ids", notInIdArr);
                LogUtil.i("PurchaseOrderAddActivity.notInIdArr:" + notInIdArr.size());
                startActivityForResult(intent, 100);
                break;
            case R.id.addPurchase_scanFood:
                scanGood(3, choiceList);
                break;
            case R.id.addPurchaseSearch_code:
                startQrCode();
                break;
            case R.id.addPurchaseSearch_search:
                if (TextUtils.isEmpty(addPurchaseSearchEdit.getText().toString().trim())) {
                    Toast.makeText(this, "請輸入貨號/條碼/名稱", Toast.LENGTH_SHORT).show();
                    return;
                }
                String info = addPurchaseSearchEdit.getText().toString().trim();
                boolean flag = false;
                for (int i = 0; i < choiceList.size(); i++) {
                    if (info.equals(choiceList.get(i).getGoods_code())) {
                        flag = true;
                        addPurchaseListView.smoothScrollToPositionFromTop(i, 0);
                        int finalI = i;
                        addPurchaseListView.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                addPurchaseListView.setSelection(finalI);
                            }
                        }, 800);
                        addDepositAdapter.setSelect(i);
                        break;
                    }
                    if (info.equals(choiceList.get(i).getSku_code())) {
                        flag = true;
                        addPurchaseListView.smoothScrollToPositionFromTop(i, 0);
                        int finalI = i;
                        addPurchaseListView.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                addPurchaseListView.setSelection(finalI);
                            }
                        }, 800);
                        addDepositAdapter.setSelect(i);
                        break;
                    }
                    if (info.equals(choiceList.get(i).getGoods_number())) {
                        flag = true;
                        addPurchaseListView.smoothScrollToPositionFromTop(i, 0);
                        int finalI = i;
                        addPurchaseListView.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                addPurchaseListView.setSelection(finalI);
                            }
                        }, 800);
                        addDepositAdapter.setSelect(i);
                        break;
                    }
                    if (info.equals(choiceList.get(i).getSku_goods_number())) {
                        flag = true;
                        addPurchaseListView.smoothScrollToPositionFromTop(i, 0);
                        int finalI = i;
                        addPurchaseListView.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                addPurchaseListView.setSelection(finalI);
                            }
                        }, 800);
                        addDepositAdapter.setSelect(i);
                        break;
                    }
                    if (info.equals(choiceList.get(i).getGoods_name())) {
                        flag = true;
                        addPurchaseListView.smoothScrollToPositionFromTop(i, 0);
                        int finalI = i;
                        addPurchaseListView.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                addPurchaseListView.setSelection(finalI);
                            }
                        }, 800);
                        addDepositAdapter.setSelect(i);
                        break;
                    }
                }
                if (!flag) {
                    Toast.makeText(this, "已選商品中暫無此商品", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.addPurchase_checkAll:
                opera = true;
                if (addPurchaseSubmit.getVisibility() == View.GONE) {
                    if (type == 0 || type == 2) {
                        if ("全選".equals(addPurchaseCheckAll.getText().toString().trim())) {
                            for (DepositGoodsInfo.DataBean.ListBean dataBean : choiceList) {
                                dataBean.setChecked(true);
                            }
                            setAddDepositAdapter();
                            addPurchaseCheckAll.setText(R.string.purRefundAdding_Choose_Item_Check_None);
                        } else {
                            for (DepositGoodsInfo.DataBean.ListBean dataBean : choiceList) {
                                dataBean.setChecked(false);
                            }
                            setAddDepositAdapter();
                            addPurchaseCheckAll.setText(R.string.purRefundAdding_check_all);
                        }
                    } else {
                        if ("全選".equals(addPurchaseCheckAll.getText().toString().trim())) {
                            for (DepositGoodsEditInfo.DataBean dataBean : editInfoList) {
                                dataBean.setChecked(true);
                            }
                            setEditDepositAdapter();
                            addPurchaseCheckAll.setText(R.string.purRefundAdding_Choose_Item_Check_None);
                        } else {
                            for (DepositGoodsEditInfo.DataBean dataBean : editInfoList) {
                                dataBean.setChecked(false);
                            }
                            setEditDepositAdapter();
                            addPurchaseCheckAll.setText(R.string.purRefundAdding_check_all);
                        }
                    }

                } else {
                    if (type == 0 || type == 2) {
                        addPurchaseSubmit.setVisibility(View.GONE);
                        addPurchaseOperation.setVisibility(View.VISIBLE);
                        addPurchaseCheckAll.setText(R.string.purRefundAdding_check_all);
                        setAddDepositAdapter();
                    } else {
                        addPurchaseSubmit.setVisibility(View.GONE);
                        addPurchaseOperation.setVisibility(View.VISIBLE);
                        addPurchaseCheckAll.setText(R.string.purRefundAdding_check_all);
                        setEditDepositAdapter();
                    }
                }
                break;
            case R.id.addPurchase_submit:
                LogUtil.e("type:" + type);

                if (type == 0 || type == 2) {//門店/商戶 提交採購單
                    if (0 == choiceList.size()) {
                        Toast.makeText(this, "請先選擇商品", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    for (int i = 0; i < choiceList.size(); i++) {
                        if (TextUtils.isEmpty(choiceList.get(i).getPurchase_price())) {
                            Toast.makeText(this, "請先設置" + choiceList.get(i).getGoods_name() + "的採購價", Toast.LENGTH_SHORT).show();
                            addPurchaseListView.smoothScrollToPositionFromTop(i, 0);
                            int finalI = i;
                            addPurchaseListView.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    addPurchaseListView.setSelection(finalI);
                                }
                            }, 800);
                            addDepositAdapter.setSelect(i);
                            return;
                        }
                        if (TextUtils.isEmpty(choiceList.get(i).getPurchase_num())) {
                            Toast.makeText(this, "請先設置" + choiceList.get(i).getGoods_name() + "的採購數量", Toast.LENGTH_SHORT).show();
                            LogUtil.i(choiceList.get(i).getGoods_name() + "的採購數量:" + choiceList.get(i).getPurchase_num());
                            addPurchaseListView.smoothScrollToPositionFromTop(i, 0);
                            int finalI = i;
                            addPurchaseListView.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    addPurchaseListView.setSelection(finalI);
                                }
                            }, 800);
                            addDepositAdapter.setSelect(i);
                            return;
                        }
                    }

                    if (0 == typeIndex) {
                        Toast.makeText(this, "請選擇採購類型", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (2 == typeIndex && TextUtils.isEmpty(time)) {
                        Toast.makeText(this, "請選擇採購日期", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (0 == warehouseIndex) {
                        Toast.makeText(this, "請選擇採購倉庫", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (0 == suppliesIndex) {
                        Toast.makeText(this, "請選擇供貨商", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    new AlertDialog.Builder(this).setTitle("提示")//設置對話框標題
                            .setMessage("確定要提交採購單？")//設置顯示的內容
                            .setPositiveButton("確定", (dialog, which) -> {//確定按鈕的響應事件
                                storePurchaseOperation();
                            }).setNegativeButton("取消", (dialog, which) -> {//取消按鈕的響應事件
                    }).show();//顯示此對話框
                } else {// 13商戶門店編輯採購單
                    if (0 == editInfoList.size()) {
                        Toast.makeText(this, "未選擇商品", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    for (int i = 0; i < editInfoList.size(); i++) {
                        DepositGoodsEditInfo.DataBean data = editInfoList.get(i);
                        if (null == data.getPurchase_price()) {
                            Toast.makeText(this, "請先設置" + data.getGoods_name() + "的採購價", Toast.LENGTH_SHORT).show();
                            addPurchaseListView.smoothScrollToPositionFromTop(i, 0);
                            return;
                        }
                        if (null == data.getPurchase_num()) {
                            Toast.makeText(this, "請先設置" + data.getGoods_name() + "的採購數量", Toast.LENGTH_SHORT).show();
                            addPurchaseListView.smoothScrollToPositionFromTop(i, 0);
                            return;
                        }
                        if (data.getPurchase_num() < data.getOperated_num()) {
                            Toast.makeText(this, data.getGoods_name() + "的採購數量不應該小於已操作數量", Toast.LENGTH_SHORT).show();
                            return;
                        }
                    }
                    if (0 == warehouseIndex) {
                        Toast.makeText(this, "請選擇採購倉庫", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (0 == suppliesIndex) {
                        Toast.makeText(this, "請選擇供貨商", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    new AlertDialog.Builder(this).setTitle("提示")//設置對話框標題
                            .setMessage("確定要提交編輯？")//設置顯示的內容
                            .setPositiveButton("確定", (dialog, which) -> {//確定按鈕的響應事件
                                updatePurchase();
                            }).setNegativeButton("取消", (dialog, which) -> {//取消按鈕的響應事件
                    }).show();//顯示此對話框
                }
                break;
            case R.id.addPurchase_complete:
                opera = false;
                addPurchaseSubmit.setVisibility(View.VISIBLE);
                addPurchaseOperation.setVisibility(View.GONE);
                addPurchaseCheckAll.setText(R.string.operation);
                setAddDepositAdapter();
                break;
            case R.id.addPurchase_delete:
                if (type == 0 || type == 2) {
                    for (int i = choiceList.size() - 1; i >= 0; i--) {
                        if (choiceList.get(i).isChecked()) {
                            notInIdArr.remove(choiceList.get(i).getId());
                            choiceList.remove(i);
                        }
                    }
                    setAddDepositAdapter();
                } else {
                    for (int i = editInfoList.size() - 1; i >= 0; i--) {
                        if (editInfoList.get(i).isChecked()) {
                            editInfoList.remove(i);
                        }
                    }
                    setEditDepositAdapter();
                }

                if (type == 0 || type == 2) {
                    if (choiceList.size() == 0) {
                        addPurchaseScreenLin.setVisibility(View.GONE);
                        addPurchaseRemarkLin.setVisibility(View.GONE);
                    } else {
                        addPurchaseScreenLin.setVisibility(View.VISIBLE);
                        addPurchaseRemarkLin.setVisibility(View.VISIBLE);
                    }
                } else {
                    if (editInfoList.size() == 0) {
                        addPurchaseScreenLin.setVisibility(View.GONE);
                        addPurchaseRemarkLin.setVisibility(View.GONE);
                    } else {
                        addPurchaseScreenLin.setVisibility(View.VISIBLE);
                        addPurchaseRemarkLin.setVisibility(View.VISIBLE);
                    }
                }

                break;
            case R.id.addPurchase_operation:
                break;
            case R.id.purchaseOrder_parchase_time:
                getDateFromDatePickerDialog(tvTime);
                time = tvTime.getText().toString();
                break;
        }
    }

    /**
     * 編輯採購單
     */
    private void updatePurchase() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        String url;
        if (type == 1) {
            url = Common.STORE_PURCHASE_EDIT;
        } else if (type == 3) {
            url = Common.MER_PURCHASE_EDIT;
        } else {
            Toast.makeText(this, "未知錯誤！", Toast.LENGTH_SHORT).show();
            return;
        }
        try {
            jsonObject.put("id", getIntent().getStringExtra("id"));
            jsonObject.put("goodsList", new Gson().toJson(editInfoList));
            jsonObject.put("supplier_id", suppliesList.get(suppliesIndex).getId());
            jsonObject.put("warehouse_id", warehouseList.get(warehouseIndex).getId());
            jsonObject.put("remarks", addPurchaseRemark.getText().toString().trim());
            HttpUtils.post(this, url, Tools.createParameterCode(jsonObject), new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    try {
                        JSONObject json = new JSONObject(text);
                        Toast.makeText(PurchaseOrderAddActivity.this, json.getString("msg"), Toast.LENGTH_SHORT).show();
                        if (json.getInt("status") == 1) {
                            finish();
                        } else {
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 提交採購單
     */
    private void storePurchaseOperation() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        LogUtil.e("storePurchaseOperation().type:" + type);
        try {
            String url = "";
            if (type == 0) {
                url = Common.STORE_PURCHASE_OPERATION;
            } else if (type == 2) {
                url = Common.MER_PURCHASE_OPERATION;
            } else {
                Toast.makeText(this, "未知錯誤！", Toast.LENGTH_SHORT).show();
                return;
            }
            jsonObject.put("user_type", aCache.getAsString("userType"));
            jsonObject.put("operator_identity_id", aCache.getAsString("uid"));
            if ("3".equals(aCache.getAsString("userType"))) {
                jsonObject.put("operator_id", aCache.getAsString("uid"));
            } else {
                jsonObject.put("operator_id", aCache.getAsString("operator_id"));
            }
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            jsonObject.put("supplier_id", suppliesList.get(suppliesIndex).getId());
            jsonObject.put("warehouse_id", warehouseList.get(warehouseIndex).getId());
            jsonObject.put("remarks", addPurchaseRemark.getText().toString().trim());
            jsonObject.put("add_time", tvTime.getText().toString().trim());
            jsonObject.put("goodsList", new Gson().toJson(choiceList));
            jsonObject.put("type", typeIndex);
            HttpUtils.post(this, url, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    try {
                        JSONObject json = new JSONObject(text);
                        Toast.makeText(PurchaseOrderAddActivity.this, json.getString("msg"), Toast.LENGTH_SHORT).show();
                        if (json.getInt("status") == 1) {
                            finish();
                        } else {
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    /**
     * 獲取採購單詳情
     */
    private void getPurchaseOrderDetail() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            String url = "";
            if (type == 1) {
                url = Common.STORE_PUR_DETAILS;
            } else if (type == 3) {
                url = Common.MER_PUR_DETAILS;
            }
            jsonObject.put("id", getIntent().getStringExtra("id"));
            HttpUtils.post(this, url, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
//                    allocationDetailInfo = GsonUtils.JsonToBean(text, AllocationDetailInfo.class);
//                    if (allocationDetailInfo.getStatus() == 1) {
//                        for (AllocationDetailInfo.DataBean dataBean : allocationDetailInfo.getData()) {
//                            DepositGoodsInfo.DataBean dataBean1 = new DepositGoodsInfo.DataBean(dataBean);
//                            choiceList.add(dataBean1);
//                        }
//                        handler.sendEmptyMessage(3);
//                    } else {
//                        handler.sendEmptyMessage(4);
//                    }
                    DepositGoodsEditInfo depositGoodsEditInfo = GsonUtils.JsonToBean(text, DepositGoodsEditInfo.class);
                    if (depositGoodsEditInfo.getStatus() == 1) {
                        editInfoList.addAll(depositGoodsEditInfo.getData());
                        handler.sendEmptyMessage(3);
                    } else {
                        handler.sendEmptyMessage(4);
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case Constant.REQ_QR_CODE:
                    Bundle bundle = data.getExtras();
                    addPurchaseSearchEdit.setText(bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN));
                    String info = addPurchaseSearchEdit.getText().toString().trim();
                    boolean flag = false;
                    for (int i = 0; i < choiceList.size(); i++) {
                        if (info.equals(choiceList.get(i).getGoods_code())) {
                            flag = true;
                            addPurchaseListView.smoothScrollToPositionFromTop(i, 0);
                            int finalI = i;
                            addPurchaseListView.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    addPurchaseListView.setSelection(finalI);
                                }
                            }, 800);
                            addDepositAdapter.setSelect(i);
                            break;
                        }
                        if (info.equals(choiceList.get(i).getSku_code())) {
                            flag = true;
                            addPurchaseListView.smoothScrollToPositionFromTop(i, 0);
                            int finalI = i;
                            addPurchaseListView.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    addPurchaseListView.setSelection(finalI);
                                }
                            }, 800);
                            addDepositAdapter.setSelect(i);
                            break;
                        }
                        if (info.equals(choiceList.get(i).getGoods_number())) {
                            flag = true;
                            addPurchaseListView.smoothScrollToPositionFromTop(i, 0);
                            int finalI = i;
                            addPurchaseListView.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    addPurchaseListView.setSelection(finalI);
                                }
                            }, 800);
                            addDepositAdapter.setSelect(i);
                            break;
                        }
                        if (info.equals(choiceList.get(i).getSku_goods_number())) {
                            flag = true;
                            addPurchaseListView.smoothScrollToPositionFromTop(i, 0);
                            int finalI = i;
                            addPurchaseListView.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    addPurchaseListView.setSelection(finalI);
                                }
                            }, 800);
                            addDepositAdapter.setSelect(i);
                            break;
                        }
                    }
                    if (!flag) {
                        Toast.makeText(this, "已選商品中暫無此商品", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case 100://選擇商品返回的數據
                    List<DepositGoodsInfo.DataBean.ListBean> backList = (List<DepositGoodsInfo.DataBean.ListBean>) data.getSerializableExtra("choice_list");
                    for (DepositGoodsInfo.DataBean.ListBean dataBean : backList) {
                        dataBean.setChecked(false);
                        notInIdArr.add(dataBean.getId());
                    }
                    choiceList.addAll(backList);
                    if (choiceList.size() > 0) {
                        addPurchaseScreenLin.setVisibility(View.VISIBLE);
                        addPurchaseRemarkLin.setVisibility(View.VISIBLE);
                    } else {
                        addPurchaseScreenLin.setVisibility(View.GONE);
                        addPurchaseRemarkLin.setVisibility(View.GONE);
                    }
                    setAddDepositAdapter();
                    break;
                case 110:
                    List<DepositGoodsInfo.DataBean.ListBean> s = (List<DepositGoodsInfo.DataBean.ListBean>) data.getSerializableExtra("list");
                    for (DepositGoodsInfo.DataBean.ListBean dataBean : s) {
                        dataBean.setChecked(false);
                        notInIdArr.add(dataBean.getId());
                    }
                    choiceList.clear();
                    choiceList.addAll(s);
                    if (choiceList.size() > 0) {
                        addPurchaseScreenLin.setVisibility(View.VISIBLE);
                        addPurchaseRemarkLin.setVisibility(View.VISIBLE);
                    } else {
                        addPurchaseScreenLin.setVisibility(View.GONE);
                        addPurchaseRemarkLin.setVisibility(View.GONE);
                    }
                    setAddDepositAdapter();
                    break;
                case 200:
                    DepositGoodsInfo.DataBean.ListBean bean = (DepositGoodsInfo.DataBean.ListBean) data.getSerializableExtra("bean");
                    int index = 0;
                    for (int t = 0; t < choiceList.size(); t++) {
                        if (bean.getGoods_id().equals(choiceList.get(t).getGoods_id())) {
                            if ("2".equals(bean.getAttribute_state())) {
                                if (bean.getSku_id().equals(choiceList.get(t).getSku_id())) {
                                    index = t;
                                    break;
                                }
                            } else {
                                index = t;
                                break;
                            }
                        }
                    }
                    choiceList.set(index, bean);
                    setAddDepositAdapter();
                    break;
                case 300:
                    DepositGoodsEditInfo.DataBean bean1 = (DepositGoodsEditInfo.DataBean) data.getSerializableExtra("bean");
                    int index1 = 0;
                    for (int t = 0; t < editInfoList.size(); t++) {
                        if (bean1.getGoods_id().equals(editInfoList.get(t).getGoods_id())) {
                            if ("2".equals(bean1.getAttribute_state())) {
                                if (bean1.getSku_id().equals(editInfoList.get(t).getSku_id())) {
                                    index1 = t;
                                    break;
                                }
                            } else {
                                index1 = t;
                                break;
                            }
                        }
                    }
                    editInfoList.set(index1, bean1);
                    setEditDepositAdapter();
                    break;
            }
        }

    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否則所有的組件都不會有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);

    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //獲取輸入框當前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 點擊的是輸入框區域，保留點擊EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
